const app = getApp()
import { getMessageCode, postLogin, getUserInfo } from '../../api/index'
import { hex_md5_salt } from '../../utils/md5'
let timer = null

Page({
  data: {
    codeIconName: 'passed',
    codeIconColor: '#09BB07',
    codeInfoColor: '#5E5E5E',
    codeMsg: '短信验证码已发送，可能会有延后请耐心等待',
    time: 0,
    isAgree: false,
    isError: false,
    isPasswrd: false,
    showAuthor: false,
    form: {
      mobile: '',
      mgCode: '',
      password: '',
      type: 2
    }
  },
  changeInput ({ detail: { value }, target: { dataset: { key } } }) {
    this.setData({
      ['form.' + key]: value 
    })
  },
  changeRadio ({ detail }) {
    this.setData({ isAgree: detail })
  },
  codeTimer () {
    this.setData({ time: 60 })
    timer = setInterval(() => {
      this.data.time--
      this.setData({ time: this.data.time })
      if (this.data.time <= 0) {
        clearInterval(timer)
      }
    }, 1000)
  },
  async sendCode () {
    try {
      let reg = /^[1][2,3,4,5,6,7,8,9][0-9]{9}$/
      if (this.data.time > 0 && this.isSendCode) {
        return
      }
      if (!this.data.form.mobile || !reg.test(this.data.form.mobile)) {
        wx.showToast({ title: '请输入正确的手机号！', icon: 'none' })
        return
      }
      this.isSendCode = true
      await getMessageCode({ mobile: this.data.form.mobile })
      this.isSendCode = false
      this.setData({
        codeIconName: 'passed',
        codeIconColor: '#09BB07',
        codeInfoColor: '#5E5E5E',
        codeMsg: '短信验证码已发送，可能会有延后请耐心等待'
      })
      await this.codeTimer()
      wx.showToast({ title: '短信验证码已发送', icon: 'none' })
    } catch (err) {
      this.isSendCode = false
      wx.showToast({ title: err.message || err.ResultSet.errors, icon: 'none' })
    }
  },
  closeAuthor () {
    this.setData({ showAuthor: false })
    wx.$nav.redirectTo('/pages/index/index')
  },
  async updateAuthor () {
    await this.getUserInfo()
    await wx.$pro.showToast({ title: '用户信息更新成功！', icon: 'none' })
    this.setData({ showAuthor: false })
    wx.$nav.redirectTo('/pages/index/index')
  },
  async getUserInfo () {
    try {
      const { ResultSet } = await getUserInfo({})
      app.globalData.userInfo = ResultSet.userData.userInfo
    } catch (err) {
      wx.showToast({ title: err.message || err.ResultSet.errors })
    }
  },
  changeloginWay () {
    this.data.isPasswrd = !this.data.isPasswrd
    this.setData({ isPasswrd: this.data.isPasswrd })
  },
  async getPhoneNumber ({ detail }) {
    try {
      console.log(detail)
      if (detail.errMsg === 'getPhoneNumber:ok') {
        const { code: loginCode } = await wx.$pro.login()
        wx.$pro.showLoading({ title: '登录中...', mask: true })
        let query = {
          loginCode,
          type: 3,
          phoneCode: detail.code
        }
        const { ResultSet } = await postLogin({ ...query })
        wx.$pro.hideLoading()
        await wx.$pro.setStorageSync('CNPASS', ResultSet.userData.token)
        await wx.$pro.setStorageSync('FIRSTLOGIN', ResultSet.userData.firstLogin)
        if (!ResultSet.userData.authorize) {
          this.setData({ showAuthor: true })
        } else {
          wx.$nav.redirectTo('/pages/index/index')
        }
      }
    } catch (err) {
      wx.$pro.hideLoading()
      this.setData({
        isError: true,
        codeIconName: 'warning-o',
        codeIconColor: '#FF2E42',
        codeInfoColor: '#FF2E42',
        codeMsg: err.message || err.ResultSet.errors
      })
    }
  },
  async login () {
    try {
      let reg = /^[1][2,3,4,5,6,7,8,9][0-9]{9}$/
      if (!reg.test(this.data.form.mobile)) {
        wx.showToast({ title: '请输入正确的手机号！', icon: 'none' })
        return
      }
      if (this.data.isPasswrd && !this.data.form.password) {
        wx.showToast({ title: '请输入密码！', icon: 'none' })
        return
      }
      if (!this.data.isPasswrd && !this.data.form.mgCode) {
        wx.showToast({ title: '请输入验证码！', icon: 'none' })
        return
      }
      if (!this.data.isPasswrd && !this.data.isAgree) {
        wx.showToast({ title: '请阅读用户服务协议！', icon: 'none' })
        return
      }
      wx.$pro.showLoading({ title: '登录中...', mask: true })
      const { code } = await wx.$pro.login()
      let query = { ...this.data.form, loginCode: code }
      if (this.data.isPasswrd) {
        query.password = hex_md5_salt(encodeURIComponent(query.password))
        query.type = 1
      } else {
        query.type = 2
      }
      const { ResultSet } = await postLogin({ ...query })
      wx.$pro.hideLoading()
      await wx.$pro.setStorageSync('CNPASS', ResultSet.userData.token)
      await wx.$pro.setStorageSync('FIRSTLOGIN', ResultSet.userData.firstLogin)
      if (!ResultSet.userData.authorize) {
        this.setData({ showAuthor: true })
      } else {
        wx.$nav.redirectTo('/pages/index/index')
      }
      // await wx.$pro.setStorage({ key: 'CNPASS', data: ResultSet.userData.token })
      // await wx.$pro.setStorage({ key: 'FIRSTLOGIN', data: ResultSet.userData.firstLogin })
      // wx.$pro.hideLoading()
      // wx.$nav.redirectTo('/pages/index/index')
    } catch (err) {
      console.log(err)
      wx.$pro.hideLoading()
      this.setData({
        isError: true,
        codeIconName: 'warning-o',
        codeIconColor: '#FF2E42',
        codeInfoColor: '#FF2E42',
        codeMsg: err.message || err.ResultSet.errors
      })
    }
  },
})
